package com.app.micaihu.view.login.activity

import android.content.Intent
import android.os.Bundle
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.bean.infor.UserInfor
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.ConfigKeyConstant
import com.app.micaihu.configure.TypeConstant
import com.app.micaihu.manager.AppConfigManager
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.utils.MobclickAgentUtils
import com.app.micaihu.view.login.contract.LogInContract
import com.app.micaihu.view.login.presenter.LogInPresenter
import com.app.micaihu.view.login.utils.CloseLoginActivityUtils
import com.app.micaihu.view.user.userinfo.activity.WebActivity
import com.app.micaihu.view.utils.loadCircleImage
import com.app.utils.biz.Biz
import com.app.utils.util.ToastUtils
import com.baidu.mobstat.StatService
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.android.synthetic.main.login_last_activity.*
import kotlinx.android.synthetic.main.login_last_activity.ivBack
import kotlinx.android.synthetic.main.login_last_activity.tvLoginAccount
import kotlinx.android.synthetic.main.login_last_activity.tvLoginCode
import kotlinx.android.synthetic.main.login_last_activity.tvPrivacyProtocol
import kotlinx.android.synthetic.main.login_last_activity.tvUserProtocol
import kotlinx.android.synthetic.main.login_other_login.*


class LastLoginActivity : BaseMvpActivity<LogInContract.View, LogInPresenter>(), LogInContract.View {

    override fun getPresenter() = LogInPresenter()
    override fun getLayoutId() = R.layout.login_last_activity

    var forceLogin = false
    private var platform: SHARE_MEDIA? = null

    private var userId: String = ""
    private val umAuthListener: UMAuthListener = object : UMAuthListener {
        override fun onStart(share_media: SHARE_MEDIA) {
            LogUtils.e(classTag, "platform onStart()$share_media")
        }

        override fun onComplete(share_media: SHARE_MEDIA, i: Int, map: Map<String, String>) {
            LogUtils.e(classTag, "platform onComplete()$share_media  ${map.toString()}")
            var nickName: String? = ""
            var headPic: String? = ""
            var fromType = ""
            var openId: String? = ""
            when (platform) {
                SHARE_MEDIA.QQ -> {
                    nickName = map["screen_name"]
                    headPic = map["profile_image_url"]
                    openId = map["openid"]
                    fromType = TypeConstant.QQ_LOGIN
                }
                SHARE_MEDIA.WEIXIN -> {
                    openId = map["openid"]
                    nickName = map["screen_name"]
                    headPic = map["profile_image_url"]
                    fromType = TypeConstant.WEIXIN_LOGIN
                }
                SHARE_MEDIA.SINA -> {
                    openId = map["id"]
                    nickName = map["screen_name"]
                    headPic = map["cover_image_phone"]
                    fromType = TypeConstant.SINA_LOGIN
                }
            }
            mPresenter?.quickLogin(openId, nickName, headPic, fromType)
        }

        override fun onError(share_media: SHARE_MEDIA, i: Int, throwable: Throwable) {
            LogUtils.e(classTag, "platform onError()$share_media  $i   $throwable")
        }

        override fun onCancel(share_media: SHARE_MEDIA, i: Int) {
            LogUtils.e(classTag, "platform onCancel()$share_media  $i  ")
        }
    }

    override fun setData() {
        BarUtils.addMarginTopEqualStatusBarHeight(ivBack)
        forceLogin = SPUtils.getInstance().getBoolean(ConfigKeyConstant.forceLogin)
        val lastUserInfo = Biz.instance.lastUserInfo
        LogUtils.e(lastUserInfo)
        if (lastUserInfo.isNotEmpty()) {
            GsonUtils.fromJson(lastUserInfo, UserInfor::class.java)?.let {
                ivHead.loadCircleImage(it.headPic, R.mipmap.image_default_round)
                tvNickName.text = it.nickName
                userId = it.uid
            }
        }
    }

    override fun addListeners() {
        ivBack.setOnClickListener {
            if (forceLogin) {
                if (ActivityUtils.isActivityExistsInStack(QuickLoginActivity::class.java)) {
                    finish()
                } else {
                    ActivityUtils.finishAllActivities()
                }
            } else {
                finish()
            }
        }
        tvLoginCode.setOnClickListener {
            enterPager(PhoneLoginActivity::class.java)
        }
        tvLoginAccount.setOnClickListener {
            enterPager(AccountLoginActivity::class.java)
        }
        tvLogin.setOnClickListener {
            if (!StringUtils.isEmpty(userId)) {
                mPresenter?.weiLogin(userId)
            }
        }
        ivQQLogin.setOnClickListener {
            platform = SHARE_MEDIA.QQ
            val installQQ = UMShareAPI.get(thisActivity).isInstall(thisActivity, SHARE_MEDIA.QQ) //判断是否本地有客户端
            if (installQQ) {
                UMShareAPI.get(thisActivity).getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                ToastUtils.makeText("请先安装QQ客户端")
            }
        }

        ivWxLogin.setOnClickListener {
            val api = UMShareAPI.get(thisActivity)
            StatService.onEvent(thisActivity, Config.EventBauduId.login_weixin, "成功", 1) // 统计的点击的次数
            MobclickAgentUtils.event(Config.EventBauduId.login_weixin, "成功")
            platform = SHARE_MEDIA.WEIXIN
            val install = api.isInstall(thisActivity, SHARE_MEDIA.WEIXIN) //判断是否本地有客户端
            if (install) {
                api.getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                MobclickAgentUtils.event(Config.EventBauduId.login_weixin, "请先安装微信客户端")
                StatService.onEvent(thisActivity, Config.EventBauduId.login_weixin, "请先安装微信客户端", 1) // 统计的点击的次数
                ToastUtils.makeText("请先安装微信客户端")
            }
        }

        ivSinaLogin.setOnClickListener {
            val api = UMShareAPI.get(thisActivity)
            StatService.onEvent(thisActivity, Config.EventBauduId.login_sina, "成功", 1) // 统计的点击的次数
            MobclickAgentUtils.event(Config.EventBauduId.login_sina, "成功")
            platform = SHARE_MEDIA.SINA
            val install = api.isInstall(thisActivity, SHARE_MEDIA.SINA) //判断是否本地有客户端
            if (install) {
                api.getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                ToastUtils.makeText("请先安装微博客户端")
            }

        }
        tvUserProtocol.setOnClickListener {
            //用户协议
            val userAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.userAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, userAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
        tvPrivacyProtocol.setOnClickListener {
            //隐私协议
            val privateAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.privateAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, privateAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
    }

    override fun handleLogin(login: BaseBean<UserInfor?>?) {
        if (login == null) {
            com.blankj.utilcode.util.ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (login.isSuccess()) {
                login.data?.let {
                    //设置用户信息
                    UserInforManager.getInstance().userInfor = it;//设置用户信息
                    //保存到本地
                    UserInforManager.getInstance().saveUserInfor(it)
                    //拉取任务数据
                    if (forceLogin) {
                        UserInforManager.getInstance().getUserTask(this, false)
                    } else {
                        UserInforManager.getInstance().getUserTask(this, true)
                    }
                    LiveEventBus.get(Config.EventBus.loginSuccess).post(true)
                    if (it.mobile.isEmpty()) {
                        val bundle = Bundle()
                        bundle.putBoolean(Config.Extra.showSkip, true)
                        enterPager(BindPhoneActivity::class.java, bundle)
                    }
                    CloseLoginActivityUtils.closeAllLoginActivity()
                }
            } else {
                ToastUtils.showText(login.msg)
            }
        }
    }

    override fun onBackPressed() {
        if (forceLogin) {
            if (ActivityUtils.isActivityExistsInStack(QuickLoginActivity::class.java)) {
                super.onBackPressed()
            } else {
                ActivityUtils.finishAllActivities()
            }
        } else {
            super.onBackPressed()
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }
}